<template>
	<view class="container">
		<!-- 表单卡片容器 -->
		<view class="form-card">
			<!-- 选择区域 -->
			<view class="form-item">
				<text class="label">选择区域</text>
				<picker class="picker" mode="selector" :range="areaList" :v-model="selectedArea" @change="onAreaChange">
					<view class="picker-content">
						<text class="picker-text">{{ areaList[selectedArea] || '请选择' }}</text>
						<uni-icons type="down" size="24" color="#999999"></uni-icons>
					</view>
				</picker>
			</view>

			<!-- 选择机台 -->
			<view class="form-item">
				<text class="label">选择机台</text>
				<picker class="picker" mode="selector" :range="machineList" :v-model="selectedMachine"
					@change="onMachineChange">
					<view class="picker-content">
						<text class="picker-text">{{ machineList[selectedMachine] || '请选择' }}</text>
						<uni-icons type="down" size="24" color="#999999"></uni-icons>
					</view>
				</picker>
			</view>

			<!-- 选择机位 -->
			<view class="form-item">
				<text class="label">选择机位</text>
				<picker class="picker" mode="selector" :range="positionList" :v-model="selectedPosition"
					@change="onPositionChange">
					<view class="picker-content">
						<text class="picker-text">{{ positionList[selectedPosition] || '请选择' }}</text>
						<uni-icons type="down" size="24" color="#999999"></uni-icons>
					</view>
				</picker>
			</view>

			<!-- 操作类型 -->
			<view class="form-item operation-type">
				<text class="label">操作类型</text>
				<radio-group class="radio-group" :v-model="operationType" @change="onOperationTypeChange">
					<label class="radio-label">
						<radio value="coin" :checked="operationType === 'coin'" />
						<text>投币</text>
					</label>
					<label class="radio-label">
						<radio value="reward" :checked="operationType === 'reward'" />
						<text>奖励</text>
					</label>
				</radio-group>
			</view>

			<!-- 启动局数 -->
			<view class="form-item" v-if="operationType !== 'reward'">
				<text class="label">启动局数</text>
				<view class="counter">
					<view class="counter-btn" @click="decrement" :class="{ 'disabled': count <= 1 }">
						<image src="/static/minus.png" mode="aspectFit" class="btn-icon"/>
					</view>
					<input type="number" class="count-input" v-model.number="count" min="1" @blur="handleCountChange" />
					<view class="counter-btn" @click="increment">
						<image src="/static/plus.png" mode="aspectFit" class="btn-icon"/>
					</view>
				</view>
			</view>

			<!-- 当前余额 -->
			<view class="form-item">
				<text class="label">当前余额</text>
				<text class="balance">
					{{ coinType==2?gameCoin:(coinType==3?amusementCoin:prepaid) }}
					{{ coinType==2?'游戏币':(coinType==3?'游乐币':'预存款') }}
				</text>
			</view>

			<!-- 合计应扣 -->
			<view class="form-item" v-if="operationType !== 'reward'">
				<text class="label">合计应扣</text>
				<text class="deduction">
					{{ count * pricePerGame }}
					{{ coinType==2?'游戏币':(coinType==3?'游乐币':'预存款') }}
				</text>
			</view>
		</view>

		<!-- 按钮区域 -->
		<view class="button-group">
				<button class="confirm-btn" @click="confirmOperation" :disabled="confirmBtnDisabled">确认</button>
			<button class="record-btn" @click="viewRecords" :disabled="confirmBtnDisabled">远程启动记录</button>
			<button class="refresh-btn" @click="refreshBalance" :disabled="confirmBtnDisabled">刷新余额</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 选择器数据
				areaList: [],
				machineList: [],
				positionList: [],

				// 原始数据存储
				areas: [],
				machines: [],
				stations: [],

				// 选中项索引
				selectedArea: 0,
				selectedMachine: 0,
				selectedPosition: 0,

				// 操作类型
				operationType: 'coin',
				coinType: 1, //1=预存款,2=游戏币,3=游乐币
				pricePerGame: 5, //每局游戏币单价
				// 启动局数
				count: 1,
				// 用户余额
				prepaid: 0,
				gameCoin: 0,
				amusementCoin: 0,
				// 确认按钮禁用状态
				confirmBtnDisabled: false,
			};
		},
		mounted() {
			// 页面加载时获取区域数据
			this.loadAreaList();
			this.loadUserBalance();
			uni.setNavigationBarTitle({
				title: this.$t('title.remoteStatr')
			});
		},
		methods: {
			// 加载区域列表
			async loadAreaList() {
				try {
					const response = await this.$http.post('/area/list/vo', {});
					if (response) {
						this.areas = response;
						this.areaList = this.areas.map(item => item.areaName);
						// 如果有数据，自动加载第一个区域的机台
						if (this.areas.length > 0) {
							this.selectedArea = 0;
							this.loadMachineList(this.areas[0].areaNo);
						}
					} else {
						uni.showToast({
							title: '获取区域数据失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取区域数据异常:', error);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			},

			// 加载机台列表
			async loadMachineList(areaNo) {
				try {
					const response = await this.$http.post('/machineSummary/getMachineListByArea', {
						areaNo
					});
					if (response) {
						this.machines = response;
						this.machineList = this.machines.map(item => item.machineName);
						// 重置机台选择
						this.selectedMachine = 0;
						this.positionList = [];
						this.stations = [];
						this.selectedPosition = 0;
						// 如果有机台数据，自动加载第一个机台的机位
						if (this.machines.length > 0) {
							this.loadPositionList(this.machines[0].machineNo);
							this.loadMachineConfig(this.machines[0].machineNo);
						}
					} else {
						uni.showToast({
							title: '获取机台数据失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取机台数据异常:', error);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			},
			// 根据机台编码查询机台配置
			async loadMachineConfig(machineNo) {
				try {
					const response = await this.$http.post('/machineSummary/getMachineConfig', {
						machineNo
					});
					if (response) {
						this.coinType = response.coinType;
						this.pricePerGame = response.pricePerGame;
					} else {
						uni.showToast({
							title: '获取机位数据失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取机位数据异常:', error);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			},
			// 加载机位列表
			async loadPositionList(machineNo) {
				try {
					const response = await this.$http.post('/station/getOnlineStationListByMachineNo', {
						machineNo
					});
					if (response) {
						this.stations = response;
						this.positionList = this.stations.map(item => item.stationName);
						this.selectedPosition = 0;
					} else {
						uni.showToast({
							title: '获取机位数据失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取机位数据异常:', error);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			},
			// 加载用户余额
			async loadUserBalance() {
				try {
					const response = await this.$http.post('/user/getUserBalance', {},{
						showLoading:false
					});
					if (response) {
						this.prepaid = response.prepaid; //预存款
						this.gameCoin = response.gameCoin; //游戏币
						this.amusementCoin = response.amusementCoin; //游乐币
					} else {
						uni.showToast({
							title: '获取用户余额失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取用户余额异常:', error);
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					});
				}
			},

			// 区域选择变化处理
			onAreaChange(e) {
				this.selectedArea = e.detail.value;
				console.log('区域选择变化:', this.selectedArea);
				if (this.areas[this.selectedArea]) {
					this.loadMachineList(this.areas[this.selectedArea].areaNo);
				}
			},
			// 机台选择变化处理
			onMachineChange(e) {
				this.selectedMachine = e.detail.value;
				console.log('机台选择变化:', this.selectedMachine);
				if (this.machines[this.selectedMachine]) {
					this.loadPositionList(this.machines[this.selectedMachine].machineNo);
					this.loadMachineConfig(this.machines[this.selectedMachine].machineNo);
				} else {
					this.positionList = [];
					this.stations = [];
					this.selectedPosition = 0;
				}
			},
			// 机位选择变化处理
			onPositionChange(e) {
				this.selectedPosition = e.detail.value;
				console.log('机位选择变化:', this.selectedPosition);
			},



			// 减少局数
			decrement() {
				if (this.count > 1) {
					this.count--;
					// 实际应用中这里应该计算合计应扣金额
				}
			},
			// 增加局数
			increment() {
				this.count++;
				// 实际应用中这里应该计算合计应扣金额
			},
			// 处理局数输入变化
			handleCountChange() {
				// 确保输入的局数为有效数字且至少为1
				if (!this.count || isNaN(this.count) || this.count < 1) {
					this.count = 1;
				} else {
					// 取整处理
					this.count = Math.floor(this.count);
				}
			},
			// 确认操作
			async confirmOperation() {
				// 验证选择是否完整
				if (!this.areas[this.selectedArea] ||
					!this.machines[this.selectedMachine] ||
					!this.stations[this.selectedPosition]) {
					uni.showToast({
						title: '请完整选择区域、机台和机位',
						icon: 'none'
					});
					return;
				}

				// 检查余额是否充足（非奖励模式）
				if (this.operationType !== 'reward') {
					const totalCost = this.count * this.pricePerGame;
					let currentBalance = 0;

					switch (this.coinType) {
						case 1:
							currentBalance = this.prepaid;
							break;
						case 2:
							currentBalance = this.gameCoin;
							break;
						case 3:
							currentBalance = this.amusementCoin;
							break;
					}

					if (currentBalance < totalCost) {
						uni.showToast({
							title: '余额不足，请充值后再试',
							icon: 'none'
						});
						return;
					}
				}

				// 显示确认对话框
				uni.showModal({
					title: '确认操作',
					content: this.operationType !== 'reward' ? `确认远程启动 ${this.count} 局？` : `确认远程启动奖励？`,
					success: async (res) => {
						if (res.confirm) {
							// 执行远程启动操作
							uni.showLoading({
								title: '上分中...'
							});
							this.executeRemoteStart().finally(() => {
								// 操作完成后刷新余额
								this.loadUserBalance().finally(() => {
									uni.hideLoading();
								});
							});
						}
					}
				});
			},
			// 查看记录
			viewRecords() {
				// 跳转到记录页面或显示记录
				uni.navigateTo({
					url: '/pages/order/remote-control-record'
				});
			},
			refreshBalance(){
				uni.showLoading({
					title: '刷新中...'
				});
				this.loadUserBalance().finally(() => {
					setTimeout(() => {
						uni.hideLoading();
					}, 500);
				});
			},
			// 执行远程启动操作
			async executeRemoteStart() {
				// 准备接口参数
				const params = {
					areaNo: this.areas[this.selectedArea].areaNo,
					machineNo: this.machines[this.selectedMachine].machineNo,
					stationNo: this.stations[this.selectedPosition].stationNo,
					operationType: this.operationType === 'reward' ? 2 : 1, // coin或reward
					roundCount: this.operationType === 'reward' ? 1 : this.count,
				};
				try {
					// 调用远程启动接口
					const response = await this.$http.post('/machineConsumptionRecord/remoteStart', params,{
						showLoading:false
					});
					if (response) {
						uni.showToast({
							title: '远程启动成功',
							icon: 'success',
							duration: 2000
						});
						// 延迟重新加载用户余额，确保toast完全显示
						setTimeout(() => {
							this.loadUserBalance();
						}, 2000);
					} else {
						uni.showToast({
							title: response?.message || '远程启动失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('远程启动异常:', error);
					uni.showToast({
						title: error.message || '远程启动异常',
						icon: 'none'
					});
				}
			},
			// 监听操作类型变化
			onOperationTypeChange(e) {
				this.operationType = e.detail.value;
				console.log('Operation type changed to:', this.operationType);
			}
		}
	};
</script>

<style scoped>
	.container {
		padding: 20rpx 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	/* 卡片容器 */
	.form-card {
		background-color: #ffffff;
		border-radius: 16rpx;
		overflow: hidden;
		margin-bottom: 20rpx;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	}

	.form-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 30rpx;
		border-bottom: 1px solid #eee;
		background-color: #fff;
	}

	.form-item:last-child {
		border-bottom: none;
	}

	.label {
		font-size: 32rpx;
		color: #333;
		width: 200rpx;
	}

	.picker {
		flex: 1;
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.picker-content {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		min-width: 0;
	}

	.picker-text {
		font-size: 32rpx;
		color: #666;
		margin-right: 10rpx;
	}

	.operation-type {
		align-items: flex-start;
		padding-top: 35rpx;
		padding-bottom: 35rpx;
	}

	.radio-group {
		flex: 1;
		display: flex;
		justify-content: flex-end;
		gap: 40rpx;
		margin-top: 6rpx;
	}

	.radio-label {
		display: flex;
		align-items: center;
		gap: 8rpx;
		font-size: 32rpx;
		color: #666;
	}

	.radio-label radio {
		transform: scale(1.2);
		margin: 0;
	}

	.counter {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	.counter-btn {
		width: 55rpx;
		height: 55rpx;
		display: flex;
	}
	.btn-icon {
		width: 55rpx;
		height: 55rpx;
	}

	.count-value {
		font-size: 32rpx;
		width: 60rpx;
		text-align: center;
	}
	.count-input {
		font-size: 32rpx;
		width: 120rpx;
		height: 60rpx;
		text-align: center;
		border: 1px solid #e0e0e0;
		border-radius: 8rpx;
		background-color: #f9f9f9;
		padding: 0;
		box-sizing: border-box;
	}

	.balance {
		font-size: 32rpx;
		color: #333;
	}

	.deduction {
		font-size: 32rpx;
		color: #ff3b30;
	}

	.button-group {
		margin-top: 60rpx;
		display: flex;
		flex-direction: column;
		gap: 30rpx;
		padding: 0 20rpx;
	}

	/* 确保按钮宽度一致 */
	.confirm-btn,
	.refresh-btn,
	.record-btn {
		height: 100rpx;
		line-height: 100rpx;
		font-size: 34rpx;
		border-radius: 16rpx;
		width: 100%;
	}

	.confirm-btn {
		background-color: #ff3b30;
		color: #fff;
	}

	.record-btn {
		background-color: #007aff;
		color: #fff;
	}
	.refresh-btn {
		background-color: #aa7934;
		color: #fff;
	}
	
	/* 按钮禁用状态样式 */
	.confirm-btn[disabled],
	.refresh-btn[disabled],
	.record-btn[disabled],
	.confirm-btn.disabled,
	.refresh-btn.disabled,
	.record-btn.disabled {
		background-color: #6e6c6c !important;
		color: #ffffff !important;
		opacity: 1 !important;
	}
</style>